<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>用户管理</title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="../static/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/css/font-awesome.min.css">
    <link rel="stylesheet" href="../static/css/ionicons.min.css">
    <link rel="stylesheet" href="../static/css/AdminLTE.min.css">
    <link rel="stylesheet" href="../static/css/skin-blue.min.css">
    <link rel="stylesheet" href="../static/css/dataTables.bootstrap.min.css">

    <style type="text/css">
        .sidebar-menu span {
            padding-left: 10px;
        }
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
    <!-- 引入头部片段 -->
    <#include "header.ftl"/>
    <!-- Menu -->
    <aside class="main-sidebar">
        <section class="sidebar">
            <ul class="sidebar-menu" data-widget="tree">
                <li class="active"><a href="/"><i class="fa fa-users fa-lg"
                                                                 style="color: lightgreen;"></i><span>用户管理</span></a>
                </li>
            </ul>
        </section>
    </aside>
    <!-- Body -->
    <div class="content-wrapper">
        <!-- Content Header (页眉) -->
        <section class="content-header">
            <h1>
                用户列表
            </h1>
        </section>

        <!-- Main content -->
        <section class="content container-fluid">
            <div class="box box-primary">
                <div class="box-header container form-horizontal" role="form">
                    <div class="form-group">
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="s_username" placeholder="请输入用户名称">
                        </div>
                        <div class="col-sm-2">
                            <button class="btn btn-primary" type="button" id="search">
                                查询
                            </button>
                            <button class="btn btn-success" id="add">新增</button>
                        </div>
                    </div>
                </div>
                <div class="box-body">
                    <table class="table table-striped" id="dataTable">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>用户名</th>
                                <th>邮箱</th>
                                <th>姓名</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </section>
        <!-- /.content -->

        <!--编辑框-->
        <div class="modal fade" id="editForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">修改用户</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input type="text" id="m_id" hidden="hidden">
                        <div class="form-group">
                            <label class="control-label" for="m_username">用户名：</label>
                            <input type="text" class="form-control" id="m_username" placeholder="">
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="m_email">邮箱：</label>
                            <input type="text" class="form-control" id="m_email" placeholder="">
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="m_truename">姓名：</label>
                            <input type="text" class="form-control" id="m_truename" placeholder="">
                        </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="modify()">提交</button>
                        </div>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal -->
        </div>
    </div>

    <!-- 引入页脚片段 -->
    <#include "footer.ftl">
</div>

<script src="../static/js/jquery.min.js"></script>
<script src="../static/js/bootstrap.min.js"></script>
<script src="../static/js/adminlte.min.js"></script>
<script src="../static/js/jquery.dataTables.min.js"></script>
<script src="../static/js/dataTables.bootstrap.min.js"></script>
<script src="../static/js/util.js"></script>

<script>
    var myTable;

    $(function () {
        //提示信息
        var lang = {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 项",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
            "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页",
                "sJump": "跳转"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        };

        myTable = $('#dataTable').DataTable(
            {
                language: lang,  //提示信息
                "iDisplayLength": 10,//默认每页数量
                //"bPaginate": true, //翻页功能
                "bLengthChange": false, //改变每页显示数据数量
                "bFilter" : false, //过滤功能
                "ordering": false,
                "bSort": false, //排序功能
                //"bInfo" : true,//页脚信息
                //"bAutoWidth" : true,//自动宽度
                "stateSave": true,
                "retrieve": true,
                "processing": true,
                "serverSide": true,
                //"bPaginate" : true,
                "bProcessing": true,//服务器端进行分页处理的意思
                ajax: function (data, callback, settings) {//ajax配置为function,手动调用异步查询
                    // 构造请求参数
                    var param = {};
                    param.draw = data.draw;
                    param.pageSize = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                    param.start = data.start;//开始的记录序号
                    param.pageNo = (data.start / data.length) + 1;//当前页码
                    //param.order = data.order[0];
                    param.username = $("#s_username").val();
                    $.ajax({
                        type: "POST",
                        url: "${ctx.contextPath}/user/list",
                        cache: false, //禁用缓存
                        data: param, //传入已封装的参数
                        dataType: "json",
                        success: function (res) {
                            // console.log(res)
                            //setTimeout仅为测试遮罩效果
                            setTimeout(
                                function () {
                                    //封装返回数据，这里仅演示了修改属性名
                                    var returnData = {};
                                    returnData.draw = res.data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                                    returnData.recordsTotal = res.data.total;
                                    returnData.recordsFiltered = res.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                                    returnData.data = res.data.records;
                                    //关闭遮罩
                                    //$wrapper.spinModal(false);
                                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                                    callback(returnData);
                                },
                                200);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert("查询失败");
                        }
                    });
                },
                "aoColumns": [
                    {
                        sTitle: '序号',
                        data: null,
                        className: 'text-center whiteSpace',
                        render:function(data,type,row,meta) {
                            return meta.row + 1 +
                                meta.settings._iDisplayStart;
                        }
                    },
                    {"data": "username"},
                    {"data": "email"},
                    {"data": "truename"},
                    {"data": "createTime",
                        render: function (data, type, row, meta) {
                            if (data){   // data不为空进行转换
                                return (new Date(data)).Format("yyyy-MM-dd hh:mm:ss");
                            } else {
                                return data = ''; //data为空时不转换
                            }
                        }
                    }
                ],

                "columnDefs": [{
                    // 定义操作列,######以下是重点########
                    "targets": 5,//操作按钮目标列
                    "data": null,
                    "render": function (data, type, row) {
                        var id = '"' + row.id
                            + '"';
                        //<a href='javascript:void(0);'  class='delete btn btn-default btn-xs'  ><i class='fa fa-times'></i> 查看</a>
                        var html = "<button class='btn btn-sm btn-warning' onclick='edit("
                            + id
                            + ")'><i class='icon-pencil'></i> 编辑</button>"
                        html += "<button class='btn btn-sm btn-danger' onclick='remove("
                            + id
                            + ")'><i class='icon-remove'></i> 删除</button>"
                        return html;
                    }
                }],
                "fnDrawCallback": function(){
                    var api = this.api();
                    //var startIndex= api.context[0]._iDisplayStart;//获取到本页开始的条数
                    api.column(0).nodes().each(function(cell, i) {
                        //此处 startIndex + i + 1;会出现翻页序号不连续，主要是因为startIndex 的原因,去掉即可。
                        //cell.innerHTML = startIndex + i + 1;
                        cell.innerHTML =  i + 1;
                    });
                }
    });

        // 新增
        $("#add").click(function () {
            reset();
            $('#editForm').modal('show');
        });

        // 搜索
        $("#search").click(function () {
            myTable.draw();
        });
    })

    function reset() {
        $("#m_id").val("");
        $("#m_username").val("");
        $("#m_email").val("");
        $("#m_truename").val("");
    }

    //删除
    function remove(id) {
        if (confirm("确定删除数据？")) {
            $.ajax({
                type: "POST",
                url: "${ctx.contextPath}user/remove",
                traditional: true,
                data: {
                    id: id
                },
                success: function (data) {
                    myTable.draw();
                },
                error: function (e) {
                    //alert("ERROR: ", e);
                    console.log("ERROR: ", e);
                }
            });
        }
    }

    function edit(id) {
        $.ajax({
            url: "${ctx.contextPath}user/" + id,
            type: "GET",
            success: function (result) {
                if (result.success) {
                    //向模态框中传值
                    $('#m_id').val(id);
                    $("#m_username").val(result.data.username);
                    $("#m_email").val(result.data.email);
                    $("#m_truename").val(result.data.truename);
                } else {
                    alert(result.data.message);
                }
            }
        });

        $('#editForm').modal('show');
    }

    //提交修改
    function modify() {
        //获取模态框数据
        var param = {};
        param.id = $("#m_id").val();
        param.username = $("#m_username").val();
        param.email = $("#m_email").val();
        param.truename = $("#m_truename").val();

        $.ajax({
            url: "${ctx.contextPath}user/modify",
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(param),
            success: function (data) {
                if (data.success) {
                    // 清空表单
                    reset();
                    $('#editForm').modal('hide');
                    myTable.draw();
                } else {
                    alert(data.message);
                }
            }
        });
    }
</script>
</body>
</html>
